import React, { useEffect, useState } from "react";
import { Routes, Route, Navigate } from "react-router-dom";
import { Spin } from "antd";
import axios from "axios";
// 路由组件
import Home from "../../view/sandbox/home/Home";
import UserList from "../../view/sandbox/user-manage/UserList";
import RoleList from "../../view/sandbox/right-manage/RoleList";
import RightList from "../../view/sandbox/right-manage/RightList";
import NoPermission from "../../view/sandbox/nopermission/NoPermission";
import NewsAdd from "../../view/sandbox/news-manage/NewsAdd";
import NewsDraft from "../../view/sandbox/news-manage/NewsDraft";
import NewsCategory from "../../view/sandbox/news-manage/NewsCategory";
import NewsPreview from "../../view/sandbox/news-manage/NewsPreview";
import NewsUpdate from "../../view/sandbox/news-manage/NewsUpdate";
import Audit from "../../view/sandbox/audit-manage/Audit";
import AuditList from "../../view/sandbox/audit-manage/AuditList";
import Unpublished from "../../view/sandbox/publish-manage/Unpublished";
import Published from "../../view/sandbox/publish-manage/Published";
import Sunset from "../../view/sandbox/publish-manage/Sunset";
import { connect } from "react-redux";
const LocalRouteMap = {
  "/home": <Home />,
  "/user-manage/list": <UserList />,
  "/right-manage/role/list": <RoleList />,
  "/right-manage/right/list": <RightList />,
  "/news-manage/add": <NewsAdd />,
  "/news-manage/draft": <NewsDraft />,
  "/news-manage/category": <NewsCategory />,
  "/news-manage/preview/:id": <NewsPreview />,
  "/news-manage/update/:id": <NewsUpdate />,
  "/audit-manage/audit": <Audit />,
  "/audit-manage/list": <AuditList />,
  "/publish-manage/unpublished": <Unpublished />,
  "/publish-manage/published": <Published />,
  "/publish-manage/sunset": <Sunset />,
};
function NewsRouter(props) {
  const [backRoutesList, setBaclRoutesList] = useState([]);
  useEffect(() => {
    // 求取url数组和总的侧边导航信息，把一级和二级菜单都请求回来，放到一个数组里，不再是嵌套关系
    Promise.all([axios.get("/rights"), axios.get("/children")]).then((res) => {
      setBaclRoutesList([...res[0].data, ...res[1].data]);
    });
  }, []);

  // 路由权限认证，因为如果不认证的化，即使当前用户看不到对应的导航，但可以通过路径访问
  const {
    role: { rights },
  } = JSON.parse(localStorage.getItem("token"));
  // 显示路由的条件之一
  const checkRoute = (item) => {
    console.log(item);
    // 判断当前有没有item.key这个路径，并且要pagepermisson====1，这样才确定它是要显示的路由
    return (
      LocalRouteMap[item.key] && (item.pagepermisson || item.routepermisson)
    ); //触发药丸事件会改变pagepermisson属性
  };
  //  显示路由的条件之二
  const checkUserPermission = (item) => {
    // 当前用户中的路由数组（url组成的）中是否包含backRoutesList（所有的url组成的数组 ）数组中的item.key
    return rights.includes(item.key);
  };
  return (
    <div>
      {/* Main部分，具体显示哪个路由 */}
      {/* 引入loading
      spinning是否正在加载中  true或fasle
      */}
      <Spin size="large" spinning={props.isLoading}>
        <Routes>
          {backRoutesList.map((item) => {
            if (checkRoute(item) && checkUserPermission(item)) {
              return (
                <Route
                  path={item.key}
                  element={LocalRouteMap[item.key]}
                  key={item.key}
                ></Route>
              );
            }
            return null;
          })}

          {/* 重定向 ：如果想去/，那么取得就是home组件*/}
          <Route path="/" element={<Navigate to="/home" />}></Route>
          {/* 如果没有匹配的路径，渲染这个组件 */}
          {backRoutesList.length > 0 && (
            <Route path="*" element={<NoPermission />}></Route>
          )}
        </Routes>
      </Spin>
    </div>
  );
}
const mapStateToProps = ({ loadingReducer: { isLoading } }) => {
  return {
    isLoading,
  };
};
// 使用react-redux
export default connect(mapStateToProps)(NewsRouter);
